const Koa = require('koa');
const https = require('https');
const bodyParser = require('koa-bodyparser');
const Router = require('@koa/router');
const renderStore = require('./renderStore');
const renderDir = require('./renderDirect');
const renderTemplate = require('./renderTemplate');
const renderStatic = require('./renderStatic');
const renderData = require('./renderData');
const renderProxy = require('./renderProxy');
const defaultRes = require('./defaultResponse');
const utils = require('./utils');

function PServer(options) {
    this.app = new Koa();
    this.router = new Router();
    this.app
    .use(this.router.routes())
    .use(this.router.allowedMethods());

    this.config = {
        port: options.port || 9000,
        root: options.root || __dirname,
        engine: options.engine, 
        templateExtension: options.templateExtension || ['.html'],
        templateData: options.templateData || {},
        routerData: options.routerData || {},
        proxy: options.proxy || {},
        store: options.store || [],
        https: !!options.https
    }

    this.store = renderStore(this.config, utils, this.app);

    this.app.use(renderProxy(this.config, utils));
    this.app.use(renderTemplate(this.config, utils));
    this.app.use(bodyParser());
    this.app.use(renderData(this.config, utils, this.store));
    this.app.use(renderDir(this.config, utils));
    this.app.use(renderStatic(this.config, utils));
    this.app.use(defaultRes(this.config, utils));


    if (this.config.https) {
        const obj = utils.createCertificate();

        https.createServer({
            key: obj.private,
            cert: obj.cert
        }, this.app.callback()).listen(this.config.port);
    } else {
        this.app.listen(this.config.port);
    }
    console.log('listen ', this.config.port);
}

module.exports = PServer;